package cn.edu.stu.service;

import cn.edu.stu.bean.AjaxResult;
import cn.edu.stu.bean.MicArtist;
import cn.edu.stu.bean.MicRecord;
import cn.edu.stu.mapper.MicArtistMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Karl
 * @Date 2022/12/16 - 23:25
 */
@Service
@Transactional
public class ArtistService {

    @Autowired
    MicArtistMapper artistMapper;


    public int checkOrInsertArtistId(String name){
        Integer result = artistMapper.selectByName(name);
        if(result==null){
            MicArtist artist = new MicArtist();
            artist.setName(name);
            artistMapper.insert(artist);
            result = artist.getId();
        }
        return result;
    }
    //浏览器传来了艺术家id，因为没有外键约束，自己判断正确性
    public boolean checkOrInsertArtistId(Integer artistId, String artist, MicRecord record) {
        if(artistId!=null){
            if (checkOrInsertArtistId(artistId)==0) {
                if(artist!=null){
                    int i = checkOrInsertArtistId(artist);
                    record.setAuthorId(i);
                    return true;
                }
            }else{
                record.setAuthorId(artistId);
                return true;
            }
        }else{
            //没有作者ID，也没有作者名字的话返回错误
            if(artist!=null){
                int i = checkOrInsertArtistId(artist);
                record.setAuthorId(i);
                return true;
            }else{
                return false;
            }
        }
        return false;
    }



    //检查id是否正确,正确则返回id,找不到则返回0
    public int checkOrInsertArtistId(Integer id){
        MicArtist result = artistMapper.selectByPrimaryKey(id);
        return result==null?0:id;
    }

    public List<MicArtist> getArtistByFuzzyName(String fuzzyName){
        //先尝试使用左前缀模糊查询返回结果，如果条数能够超过10条，则不中间模糊查询

        List<MicArtist> artists = artistMapper.selectArtistsWithLeftName(fuzzyName);
        if(artists.size()>8) return artists;
        List<Integer> ids = new LinkedList<>();
        artists.forEach(a ->{
            ids.add(a.getId());
        });

        List<MicArtist> others = artistMapper.selectArtistsWithName(fuzzyName, ids);
        artists.addAll(others);
        return artists;
    }

}
